//定义store
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义用户信息的类型
interface UserInfo {
    userId: number
    username: string
    roleId: number
    name: string | null
    phone: string | null
    department: string
    createTime: string
    updateTime: string
}

export const userInfoStore = defineStore('userInfoStore', () => {

    //定义响应式变量 - 存储完整的用户信息对象
    const userInfo = ref<UserInfo | null>(null)

    //定义修改用户信息函数
    const setUserInfo = (newUserInfo: UserInfo) => {
        userInfo.value = newUserInfo
    }

    //定义删除用户信息函数
    const removeUserInfo = () => {
        userInfo.value = null
    }

    // 计算属性：便捷访问 userId
    const userId = computed(() => {
        return userInfo.value?.userId || 0
    })

    // 计算属性：便捷访问 username
    const username = computed(() => {
        return userInfo.value?.username || ''
    })

    // 计算属性：便捷访问 roleId
    const roleId = computed(() => {
        return userInfo.value?.roleId || 0
    })

    // 计算属性：便捷访问 name
    const name = computed(() => {
        return userInfo.value?.name || ''
    })

    // 计算属性：便捷访问 phone
    const phone = computed(() => {
        return userInfo.value?.phone || ''
    })

    // 计算属性：便捷访问 department
    const department = computed(() => {
        return userInfo.value?.department || ''
    })

    // 计算属性：便捷访问 createTime
    const createTime = computed(() => {
        return userInfo.value?.createTime || ''
    })

    // 计算属性：便捷访问 updateTime
    const updateTime = computed(() => {
        return userInfo.value?.updateTime || ''
    })

    // 计算属性：检查是否有用户信息
    const hasUserInfo = computed(() => {
        return !!userInfo.value?.userId
    })

    // 计算属性：获取用户显示名称（优先使用 name，否则使用 username）
    const displayName = computed(() => {
        return userInfo.value?.name || userInfo.value?.username || '未知用户'
    })

    return {
        userInfo,
        setUserInfo,
        removeUserInfo,
        userId,
        username,
        roleId,
        name,
        phone,
        department,
        createTime,
        updateTime,
        hasUserInfo,
        displayName
    }
}
)